package cn.innosmart.aq.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.tutk.IOTC.AVIOCTRLDEFs;
import com.tutk.p2p.ConnectionManager;

import java.util.ArrayList;

import cn.innosmart.aq.R;
import cn.innosmart.aq.camera.WifiPasswordDialog;
import cn.innosmart.aq.camera.models.CameraBean;
import cn.innosmart.aq.camera.protocol.CommandCompletionHandler;
import cn.innosmart.aq.camera.protocol.CommandError;
import cn.innosmart.aq.customize.ModifyPasswordDialog;
import cn.innosmart.aq.customize.WifiListPopupWindow;
import cn.innosmart.aq.customize.cameraset.CameraVideoModePopupWindow;
import cn.innosmart.aq.customize.cameraset.CameraVideoQualityPopupWindow;
import cn.innosmart.aq.manager.CameraManager;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2015/12/18.
 */
public class CameraSetActivity extends BaseActivity {
    private final int EXIT = 2;
    private final int CANCEL = -1;
    private final int VIDEOQUALITY = 1;
    private final int VIDEOMODE = 2;
    private final int DEFAULTWIFI = 3;
    int[] videoQuality = new int[]{
            R.string.video_quality_max, R.string.video_quality_high, R.string.video_quality_in, R.string.video_quality_low, R.string.video_quality_minimum
    };
    int[] videoFlip = new int[]{
            R.string.video_flip_normal, R.string.video_flip_vertical_flip, R.string.video_flip_mirror, R.string.video_flip_flip_and_mirror
    };
    private CameraBean cameraBean;
    private Toolbar toolbar;
    private LinearLayout llModifyPassword;
    private LinearLayout llWifiManager;
    private TextView tvQuality;
    private TextView tvMode;
    private TextView tvWifiStatus;
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setResult(CANCEL);
            finish();
            overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
        }
    };
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            return true;
        }
    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case VIDEOQUALITY:
                    tvQuality.setText(getString(videoQuality[msg.arg1]));
                    break;
                case VIDEOMODE:
                    tvMode.setText(getString(videoFlip[msg.arg1]));
                    break;
                case DEFAULTWIFI:
                    tvWifiStatus.setText((CharSequence) msg.obj);
                    break;
            }
        }
    };
    private CameraVideoModePopupWindow cameraVideoModePopupWindow;
    private CameraVideoQualityPopupWindow cameraVideoQualityPopupWindow;
    private WifiListPopupWindow wifiListPopupWindow;
    private ModifyPasswordDialog modifyPasswordDialog;
    private ArrayList<AVIOCTRLDEFs.SWifiAp> wifiList = new ArrayList<>();
    private WifiPasswordDialog wifiDialog;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ll_modify_password:
                    showModifyPasswordDialog();
                    break;
                case R.id.tv_quality:
                    showVideoQualityPopupWindow();
                    break;
                case R.id.tv_mode:
                    showVideoModePopupWindow();
                    break;
                case R.id.ll_wifi_manager:
                    showWifiPopupWindow();
                    break;

            }
        }
    };

    public void showInputPasswordDialog(final AVIOCTRLDEFs.SWifiAp sWifiAp) {
        wifiDialog = new WifiPasswordDialog(this);
        final EditText etInputPassword = (EditText) wifiDialog.findViewById(R.id.et_input_password);
        wifiDialog.setTitle(R.string.dialog_title_alert);
        wifiDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String password = etInputPassword.getText().toString().trim();
                if (TextUtils.isEmpty(password)) {
                    showToast(getString(R.string.password_can_not_empty));
                    return;
                }
                cameraBean.setWifi(sWifiAp, password, new CommandCompletionHandler<Integer>() {
                    @Override
                    public void onCompletion(Integer result) {
                        if (result == 0) {
                            cameraBean.setStatus(9);
                            setResult(0x01);
                            finish();
                        }
                    }

                    @Override
                    public void onFailed(CommandError error) {

                    }
                });
                wifiDialog.dismiss();
            }
        });
        wifiDialog.setNegativeButton(getString(R.string.dialog_btn_cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wifiDialog.dismiss();
            }
        });
        wifiDialog.setCanceledOnTouchOutside(false);
        wifiDialog.show();
    }

    private void showWifiPopupWindow() {
        if (wifiListPopupWindow == null)
            wifiListPopupWindow = new WifiListPopupWindow(this, wifiList, new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    wifiListPopupWindow.dismiss();
                    AVIOCTRLDEFs.SWifiAp sWifiAp = wifiList.get(position);
                    showInputPasswordDialog(sWifiAp);
                }
            });
        wifiListPopupWindow.showAtLocation(findViewById(R.id.camera_set), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_set);
        initData();
        setBar();
        initView();
        loadingDialog();
        getData();
        cameraBean.getWifiList(new CommandCompletionHandler<ArrayList<AVIOCTRLDEFs.SWifiAp>>() {
            @Override
            public void onCompletion(ArrayList<AVIOCTRLDEFs.SWifiAp> result) {
                hideloadingDialog();
                wifiList = result;
                for (AVIOCTRLDEFs.SWifiAp wifiAp : wifiList) {
                    if (wifiAp.status == 1) {
                        Message msg = mHandler.obtainMessage();
                        msg.what = DEFAULTWIFI;
                        msg.obj = wifiAp.name;
                        mHandler.sendMessage(msg);
                        break;
                    }
                }
            }

            @Override
            public void onFailed(CommandError error) {

            }
        });
    }

    private void getData() {
        tvQuality.setText("- -");
        tvMode.setText("- -");
//        cameraBean.initCameraDevice(this);
        cameraBean.getVideoQuality(new CommandCompletionHandler<Integer>() {
            @Override
            public void onCompletion(Integer result) {
                System.out.println("VideoQuality=" + result);
                Message msg = mHandler.obtainMessage();
                msg.what = VIDEOQUALITY;
                msg.arg1 = result;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onFailed(CommandError error) {
                Message msg = mHandler.obtainMessage();
                msg.what = VIDEOQUALITY;
                msg.arg1 = -1001;
                mHandler.sendMessage(msg);
            }
        });
        cameraBean.getVideoMode(new CommandCompletionHandler<Integer>() {
            @Override
            public void onCompletion(Integer result) {
                System.out.println("VideoMode=" + result);
                Message msg = mHandler.obtainMessage();
                msg.what = VIDEOMODE;
                msg.arg1 = result;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onFailed(CommandError error) {
                Message msg = mHandler.obtainMessage();
                msg.what = VIDEOMODE;
                msg.arg1 = -1001;
                mHandler.sendMessage(msg);
            }
        });
    }

    private void showVideoModePopupWindow() {
        if (cameraVideoModePopupWindow == null)
            cameraVideoModePopupWindow = new CameraVideoModePopupWindow(this, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.video_flip_normal:
                            cameraBean.setVideoMode(0);
                            break;
                        case R.id.video_flip_vertical_flip:
                            cameraBean.setVideoMode(1);
                            break;
                        case R.id.video_flip_mirror:
                            cameraBean.setVideoMode(2);
                            break;
                        case R.id.video_flip_flip_and_mirror:
                            cameraBean.setVideoMode(3);
                            break;
                    }
                    getData();
                    cameraVideoModePopupWindow.dismiss();
                }
            });
        cameraVideoModePopupWindow.showAtLocation(findViewById(R.id.camera_set), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void showVideoQualityPopupWindow() {
        if (cameraVideoQualityPopupWindow == null)
            cameraVideoQualityPopupWindow = new CameraVideoQualityPopupWindow(this, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.video_quality_max:
                            cameraBean.setVideoQuality(0);
                            break;
                        case R.id.video_quality_high:
                            cameraBean.setVideoQuality(1);
                            break;
                        case R.id.video_quality_in:
                            cameraBean.setVideoQuality(2);
                            break;
                        case R.id.video_quality_low:
                            cameraBean.setVideoQuality(3);
                            break;
                        case R.id.video_quality_minimum:
                            cameraBean.setVideoQuality(4);
                            break;
                    }
                    getData();
                    cameraVideoQualityPopupWindow.dismiss();
                }
            });
        cameraVideoQualityPopupWindow.showAtLocation(findViewById(R.id.camera_set), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void showModifyPasswordDialog() {
        modifyPasswordDialog = new ModifyPasswordDialog(this);
        final EditText etOldPassword = (EditText) modifyPasswordDialog.findViewById(R.id.et_old_password);
//        modifyPasswordDialog.findViewById(R.id.ll_old_password).setVisibility(View.GONE);
        final EditText etNewPassword = (EditText) modifyPasswordDialog.findViewById(R.id.et_new_password);
        final EditText etNewPasswordSure = (EditText) modifyPasswordDialog.findViewById(R.id.et_new_password_sure);
        modifyPasswordDialog.setTitle(R.string.dialog_title_alert);
        modifyPasswordDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String oldPassword = etOldPassword.getText().toString().trim();
                final String newPassword = etNewPassword.getText().toString().trim();
                String newPasswordSure = etNewPasswordSure.getText().toString().trim();
                if (TextUtils.isEmpty(oldPassword)) {
                    showToast(getString(R.string.activity_countsetting_old_password_can_not_empty));
                    YoYo.with(Techniques.Shake).playOn(etOldPassword);
                    return;
                }
                if (!oldPassword.equals(cameraBean.getPsd())) {
                    showToast(getString(R.string.activity_countsetting_old_password_wrong));
                    YoYo.with(Techniques.Shake).playOn(etOldPassword);
                    return;
                }
                if (TextUtils.isEmpty(newPassword)) {
                    showToast(getString(R.string.activity_countsetting_input_new_password));
                    YoYo.with(Techniques.Shake).playOn(etNewPassword);
                    return;
                }
                if (TextUtils.isEmpty(newPasswordSure)) {
                    showToast(getString(R.string.activity_countsetting_sure_new_password));
                    YoYo.with(Techniques.Shake).playOn(etNewPasswordSure);
                    return;
                }
                if (!newPassword.equals(newPasswordSure)) {
                    showToast(getString(R.string.activity_countsetting_twice_password_not_same));
                    YoYo.with(Techniques.Shake).playOn(etNewPassword);
                    YoYo.with(Techniques.Shake).playOn(etNewPasswordSure);
                    return;
                }
                modifyPasswordDialog.dismiss();
                loadingDialog();
                cameraBean.setPassword(oldPassword, newPassword, new CommandCompletionHandler<Integer>() {
                    @Override
                    public void onCompletion(Integer result) {

                    }

                    @Override
                    public void onFailed(CommandError error) {

                    }
                });
                cameraBean.setPsd(newPassword);
                CameraManager.getInstance().Update(ConnectionManager.getInstance().getCurrentConnectionEntity(), cameraBean.toUpdateParam(), new CameraManager.UpdateCallBack() {
                    @Override
                    public void onUpdateResponseCallBack(int ret) {
                        hideloadingDialog();
                    }
                });
            }
        });
        modifyPasswordDialog.setNegativeButton(getString(R.string.dialog_btn_cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyPasswordDialog.dismiss();
            }
        });
        modifyPasswordDialog.setCanceledOnTouchOutside(false);
        modifyPasswordDialog.show();
    }


    private void initView() {
        llModifyPassword = (LinearLayout) findViewById(R.id.ll_modify_password);
        llWifiManager = (LinearLayout) findViewById(R.id.ll_wifi_manager);
        tvQuality = (TextView) findViewById(R.id.tv_quality);
        tvMode = (TextView) findViewById(R.id.tv_mode);
        tvWifiStatus = (TextView) findViewById(R.id.tv_wifi_status);
        tvQuality.setOnClickListener(onClickListener);
        tvMode.setOnClickListener(onClickListener);
        llModifyPassword.setOnClickListener(onClickListener);
        llWifiManager.setOnClickListener(onClickListener);
    }

    private void initData() {
        Intent intent = getIntent();
        String cameraId = intent.getStringExtra("CameraBean");
        cameraBean = SystemConstant.cameraBeanHashMap.get(cameraId);
    }

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.camera_set));
        setSupportActionBar(toolbar);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(CANCEL);
                finish();
                overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
            }
        });
        toolbar.setOnMenuItemClickListener(onMenuItemClick);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }
}
